package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.dataobject.IotCard;
import com.bbzn.device.client.service.DeviceService;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.IotCardService;
import com.bbzn.device.client.utils.OptionalBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: wulongbo
 * @Date : 2021/4/9 11:19
 * @Version 1.0
 */
@Component
public class EmqIccidUploadStrategy implements EmqStrategy {

    @Resource
    private DeviceService deviceService;

    @Resource
    private IotCardService iotCardService;

    // 设备上传卡号电话号码
    @Override
    public String emqAction(String payLoad) {
        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            String imei = jsonObject.getString("imei");
            if (!OptionalBean.ofNullable(imei).isPresent()) {
                return "json解析错误";
            }
            String iccid = jsonObject.getString("iccid");
            if (!OptionalBean.ofNullable(iccid).isPresent()) {
                return "json解析错误";
            }
            Device device = new Device();
            device.setImei(imei);
            device.setIccid(iccid);
            deviceService.updateByImeiSelective(device);

            IotCard iotCard = new IotCard();
            iotCard.setImei(imei);
            iotCard.setCardNum(iccid);
            iotCardService.updateByIccidSelective(iotCard);
        } catch (Exception e) {
            return "设备上传卡号电话号码失败！";
        }
        return "设备上传卡号电话号码成功！";
    }
}
